home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / prolog / sbprolog / v3 / modlib_s.lha / modlib_src / $setof.P < prev    next >
Text File  |  1990-04-12  |  18KB  |  535 lines

  1. /* $setof.P */
  2.  
  3. %   File   : SETOF.PL
  4. %   Author : R.A.O'Keefe
  5. %   Updated: 17 November 1983
  6. %   Purpose: define set_of/3, bag_of/3, findall/3, and findall/4
  7. %   Needs  : Not.Pl
  8. %
  9. %   Modified for SB-Prolog by Saumya K. Debray, May 1988.
  10. %   Some of the code for the SB-Prolog version, specifically
  11. %   the version of $findall/3 using buff_code, was written by
  12. %   David S. Warren (in 1986?).
  13.  
  14. /*  This file defines two predicates which act like setof/3 and bagof/3.
  15.     I have seen the code for these routines in Dec-10 and in C-Prolog,
  16.     but I no longer recall it, and this code was independently derived
  17.     in 1982 by me and me alone.
  18.  
  19.     Most of the complication comes from trying to cope with free variables
  20.     in the Filter; these definitions actually enumerate all the solutions,
  21.     then group together those with the same bindings for the free variables.
  22.     There must be a better way of doing this.  I do not claim any virtue for
  23.     this code other than the virtue of working.  In fact there is a subtle
  24.     bug: if setof/bagof occurs as a data structure in the Generator it will
  25.     be mistaken for a call, and free variables treated wrongly.  Given the
  26.     current nature of Prolog, there is no way of telling a call from a data
  27.     structure, and since nested calls are FAR more likely than use as a
  28.     data structure, we just put up with the latter being wrong.  The same
  29.     applies to negation.
  30.  
  31.     Would anyone incorporating this in their Prolog system please credit
  32.     both me and David Warren;  he thought up the definitions, and my
  33.     implementation may owe more to subconscious memory of his than I like
  34.     to think.  At least this ought to put a stop to fraudulent claims to
  35.     having bagof, by replacing them with genuine claims.
  36.  
  37.     Thanks to Dave Bowen for pointing out an amazingly obscure bug: if
  38.     the Template was a variable and the Generator never bound it at all
  39.     you got a very strange answer!  Now fixed, at a price.
  40. */
  41.  
  42. /*
  43. :- public
  44.     findall/3,        %   Same effect as C&M p152
  45.     findall/4,        %   A variant I have found very useful
  46.     bag_of/3,        %   Like bagof (Dec-10 manual p52)
  47.     set_of/3.        %   Like setof (Dec-10 manual p51)
  48.  
  49. :- mode
  50.     bag_of(+,+,?),
  51.     concordant_subset(+,+,-),
  52.     concordant_subset(+,+,-,-),
  53.     concordant_subset(+,+,+,+,-),
  54.     findall(+,+,?),
  55.     findall(+,+,+,?),
  56.     list_instances(+,-),
  57.     list_instances(+,+,-),
  58.     list_instances(+,+,+,-),
  59.     list_instances(+,+,+,+,-),
  60.     replace_key_variables(+,+,+),
  61.     save_instances(+,+),
  62.     set_of(+,+,?).
  63.  
  64. */
  65.  
  66. $setof_export([$setof/3,$bagof/3,$findall/3,$sort/2,$keysort/3]).
  67.  
  68. /* $setof_use($meta,[$functor/3,$univ/2,$length/2]).
  69.    $setof_use($buff,[$alloc_perm/2,$alloc_heap/2,$trimbuff/3,$buff_code/4,
  70.         $symtype/2,
  71.         $substring/6,$subnumber/6,$subdelim/6,$conlength/2,
  72.         $pred_undefined/1, $hashval/3]).
  73.    $setof_use($bmeta,[$atom/1,$atomic/1,$integer/1,$number/1,$structure/1,
  74.     $functor0/2,$bldstr/3,$arg/3,$arity/2,$real/1,$floor/2]).
  75. */
  76.  
  77. %   findall(Template, Generator, List)
  78. %   is a special case of bagof, where all free variables in the
  79. %   generator are taken to be existentially quantified.  It is
  80. %   described in Clocksin & Mellish on p152.  The code they give
  81. %   has a bug (which the Dec-10 bagof and setof predicates share)
  82. %   which this has not.
  83.  
  84. /*
  85. % SB-Prolog doesn't have record/recorded, so we use buff_code.
  86.  
  87. findall(Template, Generator, List) :-
  88.     save_instances(-Template, Generator),
  89.     list_instances([], List).
  90.  
  91. */
  92.  
  93.  
  94. $findall(T,Call,Result) :-
  95.     $alloc_heap(10000,Buff),
  96.     $findall_1(T,Call,Result,Buff).
  97.  
  98. $findall_1(T,Call,Result,Buff) :-
  99.     $copyterm([],Buff,8,4,_), /* init result list to empty */
  100.     $buff_code(Buff,0,2 /*pn*/ ,8), /* init where to put next answer */
  101.     $buff_code(Buff,4,2 /*pn*/ ,12), /* init first free place */
  102.     call(Call),
  103.     $buff_code(Buff,0,5 /*gn*/ ,Place), /* get where to put answer */
  104.     $buff_code(Buff,4,5 /*gn*/ ,Start), /* get first free place */
  105.     $copyterm([T],Buff,Place,Start,End),
  106.     Tailloc is Start+4,    
  107.     $buff_code(Buff,0,2 /*pn*/ ,Tailloc), /* where to put next answer */
  108.     $buff_code(Buff,4,2 /*pn*/ ,End), /* next first free place */
  109.     fail.
  110.  
  111. $findall_1(_,_,Result,Buff) :-
  112.     $buff_code(Buff,4,5 /*gn*/ ,Length), /* Length =\= 12 fail if [] */
  113.     $trimbuff(Length,Buff,1),
  114.     $buff_code(Buff,8,18 /*vtb*/ ,Result).
  115.  
  116. %   findall(Template, Generator, SoFar, List) :-
  117. %    findall(Template, Generator, Solns),
  118. %    append(Solns, SoFar, List).
  119. %   But done more cheaply.
  120. %
  121. % findall/4 commented out for SB-Prolog since the current version
  122. % of SB-Prolog doesn't have record/recorded/erase
  123. %
  124. % findall(Template, Generator, SoFar, List) :-
  125. %    save_instances(-Template, Generator),
  126. %    list_instances(SoFar, List).
  127.  
  128.  
  129. %   $setof(Template, Generator, Set)
  130. %   finds the Set of instances of the Template satisfying the Generator.
  131. %   The set is in ascending order (see compare/3 for a definition of
  132. %   this order) without duplicates, and is non-empty.  If there are
  133. %   no solutions, set_of fails.  set_of may succeed more than one way,
  134. %   binding free variables in the Generator to different values.  This
  135. %   predicate is defined on p51 of the Dec-10 Prolog manual.
  136.  
  137. $setof(Template, Filter, Set) :-
  138.     $bagof(Template, Filter, Bag),
  139.     $sort(Bag, Set).
  140.  
  141.  
  142.  
  143. %   $bagof(Template, Generator, Bag)
  144. %   finds all the instances of the Template produced by the Generator,
  145. %   and returns them in the Bag in they order in which they were found.
  146. %   If the Generator contains free variables which are not bound in the
  147. %   Template, it assumes that this is like any other Prolog question
  148. %   and that you want bindings for those variables.  (You can tell it
  149. %   not to bother by using existential quantifiers.)
  150. %   bag_of records three things under the key '.':
  151. %    the end-of-bag marker           -
  152. %    terms with no free variables   -Term
  153. %    terms with free variables   Key-Term
  154. %   The key '.' was chosen on the grounds that most people are unlikely
  155. %   to realise that you can use it at all, another good key might be ''.
  156. %   The original data base is restored after this call, so that set_of
  157. %   and bag_of can be nested.  If the Generator smashes the data base
  158. %   you are asking for trouble and will probably get it.
  159. %   The second clause is basically just findall, which of course works in
  160. %   the common case when there are no free variables.
  161. %
  162. % SB-Prolog version modified to use findall instead of record/recorded - SKD
  163. %
  164.  
  165. $bagof(Template, Generator, Bag) :-
  166.     free_variables(Generator, Template, [], Vars),
  167.     Vars \= [],
  168.     !,
  169.     Key =.. [.|Vars],
  170.     functor(Key, ., N),
  171.         $findall(Key-Template,Generator,OmniumGatherum),
  172.     $keysort(OmniumGatherum, Gamut), !,
  173.     concordant_subset(Gamut, Key, Answer),
  174.     Bag = Answer.
  175. $bagof(Template, Generator, Bag) :-
  176.         $findall(Template,Generator,Bag).
  177.  
  178. /***********
  179. %   save_instances(Template, Generator)
  180. %   enumerates all provable instances of the Generator and records the
  181. %   associated Template instances.  Neither argument ends up changed.
  182.  
  183. save_instances(Template, Generator) :-
  184.     recorda(., -, _),
  185.     call(Generator),
  186.     recorda(., Template, _),
  187.     fail.
  188. save_instances(_, _).
  189.  
  190. %   list_instances(SoFar, Total)
  191. %   pulls all the -Template instances out of the data base until it
  192. %   hits the - marker, and puts them on the front of the accumulator
  193. %   SoFar.  This routine is used by findall/3-4 and by bag_of when
  194. %   the Generator has no free variables.
  195.  
  196. list_instances(SoFar, Total) :-
  197.     recorded(., Term, Ref),
  198.     erase(Ref), !,        %   must not backtrack
  199.     list_instances(Term, SoFar, Total).
  200.  
  201. list_instances(-, SoFar, Total) :- !,
  202.     Total = SoFar.        %   = delayed in case Total was bound
  203. list_instances(-Template, SoFar, Total) :-
  204.     list_instances([Template|SoFar], Total).
  205.  
  206. %   list_instances(Key, NVars, BagIn, BagOut)
  207. %   pulls all the Key-Template instances out of the data base until
  208. %   it hits the - marker.  The Generator should not touch recordx(.,_,_).
  209. %   Note that asserting something into the data base and pulling it out
  210. %   again renames all the variables; to counteract this we use replace_
  211. %   key_variables to put the old variables back.  Fortunately if we
  212. %   bind X=Y, the newer variable will be bound to the older, and the
  213. %   original key variables are guaranteed to be older than the new ones.
  214. %   This replacement must be done @i<before> the keysort.
  215.  
  216. list_instances(Key, NVars, OldBag, NewBag) :-
  217.     recorded(., Term, Ref),
  218.     erase(Ref), !,        %  must not backtrack!
  219.     list_instances(Term, Key, NVars, OldBag, NewBag).
  220.  
  221.  
  222. list_instances(-, _, _, AnsBag, AnsBag) :- !.
  223. list_instances(NewKey-Term, Key, NVars, OldBag, NewBag) :-
  224.     replace_key_variables(NVars, Key, NewKey), !,
  225.     list_instances(Key, NVars, [NewKey-Term|OldBag], NewBag).
  226. ********** */
  227.  
  228.  
  229. %   There is a bug in the compiled version of arg in Dec-10 Prolog,
  230. %   hence the rather strange code.  Only two calls on arg are needed
  231. %   in Dec-10 interpreted Prolog or C-Prolog.
  232.  
  233. replace_key_variables(0, _, _) :- !.
  234. replace_key_variables(N, OldKey, NewKey) :-
  235.     arg(N, NewKey, Arg),
  236.     nonvar(Arg), !,
  237.     M is N-1,
  238.     replace_key_variables(M, OldKey, NewKey).
  239. replace_key_variables(N, OldKey, NewKey) :-
  240.     arg(N, OldKey, OldVar),
  241.     arg(N, NewKey, OldVar),
  242.     M is N-1,
  243.     replace_key_variables(M, OldKey, NewKey).
  244.  
  245.  
  246.  
  247. %   concordant_subset([Key-Val list], Key, [Val list]).
  248. %   takes a list of Key-Val pairs which has been keysorted to bring
  249. %   all the identical keys together, and enumerates each different
  250. %   Key and the corresponding lists of values.
  251.  
  252. concordant_subset([Key-Val|Rest], Clavis, Answer) :-
  253.     concordant_subset(Rest, Key, List, More),
  254.     concordant_subset(More, Key, [Val|List], Clavis, Answer).
  255.  
  256.  
  257. %   concordant_subset(Rest, Key, List, More)
  258. %   strips off all the Key-Val pairs from the from of Rest,
  259. %   putting the Val elements into List, and returning the
  260. %   left-over pairs, if any, as More.
  261.  
  262. concordant_subset([Key-Val|Rest], Clavis, [Val|List], More) :-
  263.     Key == Clavis,
  264.     !,
  265.     concordant_subset(Rest, Clavis, List, More).
  266. concordant_subset(More, _, [], More).
  267.  
  268.  
  269. %   concordant_subset/5 tries the current subset, and if that
  270. %   doesn't work if backs up and tries the next subset.  The
  271. %   first clause is there to save a choice point when this is
  272. %   the last possible subset.
  273.  
  274. concordant_subset([],   Key, Subset, Key, Subset) :- !.
  275. concordant_subset(_,    Key, Subset, Key, Subset).
  276. concordant_subset(More, _,   _,   Clavis, Answer) :-
  277.     concordant_subset(More, Clavis, Answer).
  278.  
  279.  
  280. %   File   : NOT.PL
  281. %   Author : R.A.O'Keefe
  282. %   Updated: 17 November 1983
  283. %   Purpose: "suspicious" negation 
  284.  
  285. /*  This file defines a version of 'not' which checks that there are
  286.     no free variables in the goal it is given to "disprove".  Bound
  287.     variables introduced by the existential quantifier ^ or set/bag
  288.     dummy variables are accepted.  If any free variables are found, 
  289.     a message is printed on the terminal and a break level entered.
  290.  
  291.     It is intended purely as a debugging aid, though it shouldn't slow
  292.     interpreted code down much.  There are several other debugging
  293.     aids that you might want to use as well, particularly
  294.     unknown(_, trace)
  295.     which will detect calls to undefined predicates (as opposed to
  296.     predicates which have clauses that don't happen to match).
  297.  
  298.     The predicate free_variables/4 defined in this files is also used
  299.     by the set_of/bag_of code.
  300.  
  301.     Note: in Dec-10 Prolog you should normally use "\+ Goal" instead
  302.     of "not(Goal)".  In C-Prolog you can use either, and would have to
  303.     do some surgery on pl/init to install this version of "not".  The
  304.     reason that I have called this predicate "not" is so that people
  305.     can choose whether to use the library predicate not/1 (in Invoca.Pl)
  306.     or this debugging one, not because I like the name.
  307. */
  308.  
  309. /*
  310. :- public
  311.     (not)/1.        %   new checking denial
  312.  
  313. :- mode
  314.     explicit_binding(+,+,-,-),
  315.     free_variables(+,+,+,-),
  316.         free_variables(+,+,+,+,-),
  317.     list_is_free_of(+,+),
  318.     not(+),
  319.     term_is_free_of(+,+),
  320.         term_is_free_of(+,+,+).
  321.  
  322. :- op(900, fy, not).
  323.  
  324. not(Goal) :-
  325.     free_variables(Goal, [], [], Vars),
  326.     Vars \== [], !,
  327.     fwritef(user, '\n! free variables %t\n! in goal not(%t)\n',
  328.         [Vars,Goal]),
  329.     break,
  330.     call(Goal),
  331.     !, fail.
  332. not(Goal) :-
  333.     call(Goal),
  334.     !, fail.
  335. not(_).
  336. */
  337.  
  338.  
  339. %   In order to handle variables properly, we have to find all the 
  340. %   universally quantified variables in the Generator.  All variables
  341. %   as yet unbound are universally quantified, unless
  342. %    a)  they occur in the template
  343. %    b)  they are bound by X^P, setof, or bagof
  344. %   free_variables(Generator, Template, OldList, NewList)
  345. %   finds this set, using OldList as an accumulator.
  346.  
  347. free_variables(Term, Bound, VarList, [Term|VarList]) :-
  348.     var(Term),
  349.     term_is_free_of(Bound, Term),
  350.     list_is_free_of(VarList, Term),
  351.     !.
  352. free_variables(Term,_Bound, VarList, VarList) :-
  353.     var(Term),
  354.     !.
  355. free_variables(Term, Bound, OldList, NewList) :-
  356.     explicit_binding(Term, Bound, NewTerm, NewBound),
  357.     !,
  358.     free_variables(NewTerm, NewBound, OldList, NewList).
  359. free_variables(Term, Bound, OldList, NewList) :-
  360.     functor(Term, _, N),
  361.     free_variables(N, Term, Bound, OldList, NewList).
  362.  
  363. free_variables(0,_Term,_Bound, VarList, VarList) :- !.
  364. free_variables(N, Term, Bound, OldList, NewList) :-
  365.     arg(N, Term, Argument),
  366.     free_variables(Argument, Bound, OldList, MidList),
  367.     M is N-1, !,
  368.     free_variables(M, Term, Bound, MidList, NewList).
  369.  
  370. %   explicit_binding checks for goals known to existentially quantify
  371. %   one or more variables.  In particular \+ is quite common.
  372.  
  373. explicit_binding(\+ _Goal,           Bound, fail,    Bound      ) :- !.
  374. explicit_binding(not(_Goal),           Bound, fail,    Bound       ) :- !.
  375. explicit_binding(Var^Goal,           Bound, Goal,    Bound+Var) :- !.
  376. explicit_binding(setof(Var,Goal,Set),  Bound, Goal-Set, Bound+Var) :- !.
  377. explicit_binding(bagof(Var,Goal,Bag),  Bound, Goal-Bag, Bound+Var) :- !.
  378. explicit_binding(set_of(Var,Goal,Set), Bound, Goal-Set, Bound+Var) :- !.
  379. explicit_binding(bag_of(Var,Goal,Bag), Bound, Goal-Bag, Bound+Var) :- !.
  380.  
  381.  
  382. term_is_free_of(Term, Var) :-
  383.     var(Term), !,
  384.     Term \== Var.
  385. term_is_free_of(Term, Var) :-
  386.     functor(Term, _, N),
  387.     term_is_free_of(N, Term, Var).
  388.  
  389. term_is_free_of(0,_Term,_Var) :- !.
  390. term_is_free_of(N, Term, Var) :-
  391.     arg(N, Term, Argument),
  392.     term_is_free_of(Argument, Var),
  393.     M is N-1, !,
  394.     term_is_free_of(M, Term, Var).
  395.  
  396.  
  397. list_is_free_of([Head|Tail], Var) :-
  398.     Head \== Var,
  399.     !,
  400.     list_is_free_of(Tail, Var).
  401. list_is_free_of([], _).
  402.  
  403. /*======================================================================*/
  404.  
  405. /* This routine copies a term into a buffer. It is passed:
  406.     Term: the term to copy,
  407.     Buffer: the buffer to copy it into,
  408.     Worddisp: the word of the buffer in which to put the copy (or
  409.         a pointer to the copy.)
  410.     Start: the disp of the next free location in the buffer, before the 
  411.         copy is done.
  412.     End: (returned) the location of the first free location after the
  413.         copying.
  414.  
  415.     Variables are copied into the buffer and the copied variables are
  416.     pointed into the buffer and trailed. Thus later binding of these 
  417.     `outside' variables will cause the copied variables to be changed,
  418.     too. If, however, the $copyterm call is failed over, the variables
  419.     in the buffer will be ``disconnected'' from the outer variables.
  420.  
  421.     Copyterm is a prime candidate for moving down into the simulator as
  422.     a builtin written in C.
  423. */
  424.  
  425.  
  426. $copyterm(Term,Buff,Worddisp,Start,Start) :-
  427.     var(Term),!,$buff_code(Buff,Worddisp,17 /*pvar*/ ,Term).
  428.  
  429. $copyterm(Term,Buff,Worddisp,Start,Start) :-
  430.     number(Term),!,$buff_code(Buff,Worddisp,14 /*ptv*/ ,Term).
  431.  
  432. $copyterm(Term,Buff,Worddisp,Start,Start) :-
  433.     $atom(Term),!,$buff_code(Buff,Worddisp,14 /*ptv*/ ,Term).
  434.  
  435. $copyterm(Term,Buff,Worddisp,Start,End) :-
  436.     Term=[_|_],!,
  437.     $buff_code(Buff,Worddisp,16 /*ptl*/ ,Start), /* ptr to list rec */
  438.     Newstart is Start+8, /* reserve rec space */
  439.     $copyargs(Term,1,2,Buff,Start,Newstart,End).
  440.     
  441. $copyterm(Term,Buff,Worddisp,Start,End) :-
  442.     $structure(Term),!,
  443.     $buff_code(Buff,Worddisp,15 /*ptp*/ ,Start), /* ptr to str rec */
  444.     $buff_code(Buff,Start,0 /*ppsc*/ ,Term), /* rec psc ptr */
  445.     Argsloc is Start+4,
  446.     $arity(Term,Arity),Newstart is Argsloc+4*Arity, /* reserve rec space*/
  447.     $copyargs(Term,1,Arity,Buff,Argsloc,Newstart,End).
  448.     
  449. $copyargs(Term,Argno,Maxargs,Buff,Argloc,Start,End) :- 
  450.     Argno > Maxargs,
  451.      Start=End;
  452.     Argno =< Maxargs,
  453.      arg(Argno,Term,Arg),$copyterm(Arg,Buff,Argloc,Start,Mid),
  454.      Nargno is Argno+1, Nargloc is Argloc+4,
  455.      $copyargs(Term,Nargno,Maxargs,Buff,Nargloc,Mid,End).
  456.  
  457.  
  458. $sort(L,R) :- $length(L,N), $sort(N,L,_,R).
  459.  
  460. $sort(N,U,L,R) :-
  461.     N > 2 ->
  462.         (N1 is N >> 1, N2 is N-N1,
  463.          $sort(N1,U,L2,R1),
  464.          $sort(N2,L2,L,R2),
  465.          $merge(R1,R2,R)
  466.         ) ;
  467.         (N =:= 2 ->
  468.             (U = [X1|L1],
  469.              L1 = [X2|L],
  470.              compare(Delta,X1,X2),
  471.              (Delta ?= (<) -> R = [X1,X2] ;
  472.               Delta ?= (>) -> R = [X2,X1] ;
  473.                         R = [X2]
  474.              )
  475.             ) ;
  476.             (N =:= 1 ->
  477.                 (U = [X|L], R = [X]) ;
  478.                 (U = L, R = [])        /* N == 0 */
  479.             )
  480.          ).
  481.  
  482. $merge(R1,R2,R3) :-
  483.    R1 ?= [] ->
  484.        R3 = R2 ;
  485.    R2 ?= [] ->
  486.        R3 = R1 ;
  487.        (R1 = [X1|R1a], R2 = [X2|R2a], R3 = [X|R],
  488.         compare(Delta,X1,X2),
  489.         (Delta ?= (<) ->
  490.             (X = X1, $merge(R1a,R2,R)) ;
  491.             (Delta ?= (>) ->
  492.                 (X = X2, $merge(R1,R2a,R)) ;
  493.             (X = X1, $merge(R1a,R2a,R))
  494.             )
  495.     )
  496.        ).
  497.  
  498. /* Sorting on keys by bisecting and merging. */
  499.  
  500. $keysort(L,R) :- $length(L,N), $keysort(N,L,_,R1), R=R1.
  501.  
  502. $keysort(N,U,L,R) :-
  503.     N > 2 ->
  504.          (N1 is N >> 1, N2 is N-N1,
  505.           $keysort(N1,U,L2,R1),
  506.              $keysort(N2,L2,L,R2),
  507.              $keymerge(R1,R2,R)
  508.          ) ;
  509.         (N =:= 2 ->
  510.          (U = [X1|L1],
  511.           L1 = [X2|L],
  512.           $compare_keys(Delta,X1,X2),
  513.           (Delta ?= (>) -> R = [X2,X1] ; R = [X1,X2])
  514.          ) ;
  515.     (N =:= 1 ->
  516.          (U = [X|L], R = [X]) ;
  517.          (U = L, R = [])        /* N == 0 */
  518.          )).
  519.  
  520. $keymerge([],R,R) :- !.
  521. $keymerge(R,[],R) :- !.
  522. $keymerge(R1,R2,[X|R]) :-
  523.    R1 = [X1|R1a], R2 = [X2|R2a],
  524.    $compare_keys(Delta,X1,X2),
  525.   (Delta ?= (>) ->
  526.        (X = X2, $keymerge(R1,R2a,R)) ;
  527.        (X = X1, $keymerge(R1a,R2,R))
  528.   ).
  529.  
  530. $compare_keys(Delta,K1-X1,K2-X2) :- compare(Delta,K1,K2).
  531.  
  532. X^P :- call(P).
  533.  
  534. /* ------------------------------ $setof.P ------------------------------ */
  535.